package com.tn.service.weigh.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.listenvision.test;
import com.tn.controller.alarm.common.model.weigh.mq.LicenseDto;
import com.tn.dao.weigh.IWeighDao;
import com.tn.mqtt.AbstractBaseCallback;

import com.tn.properties.WeighLedIpProperties;
import com.tn.utils.HexUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.List;



/**
*@Author: Suzuki
*@CreateTime: 2022/10/19-17:21
*@Description: 车牌号mq
*@Version: 1.0
**/
@Component
@Slf4j
public class LicenseMQ extends AbstractBaseCallback {
    private final static  String topic = "rpm/weight";


    public static float weigh=0f;

    @Value("${raster-url}")
    private String rasterUrl;


    @Autowired
    private IWeighDao weighDao;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void consumer(String topic, String msg) {
        //消息存入
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String type = jsonObject.get("type").toString();
        if("license".equals(type)){
            String location = jsonObject.get("location").toString();
            log.info("LicenseMQ topic:{}, 消息是 msg:{}",topic,msg);
            String license = jsonObject.get("license") != null ? jsonObject.get("license").toString() : null;
            if(license != null){
                try {
                    WeighLedIpProperties.WeighChannelIp ledIp = WeighLedIpProperties.getLedIp(location);
                    if (ledIp == null) {
                        log.error("编号为{}地磅未配置屏幕Ip，当前车牌号为{}", location, license);
                    } else {
                        log.info("成功获取编号为{}地磅的Led屏幕Ip{}", location, JSON.toJSONString(ledIp));
                        if(StringUtils.isNotBlank(ledIp.getLeft())){
                            test.onPowerOnOff(ledIp.getLeft());
                            test.showTwoLine(ledIp.getLeft(),license);
                        }
                        if(StringUtils.isNotBlank(ledIp.getRight())){
                            test.onPowerOnOff(ledIp.getRight());
                            test.showTwoLine(ledIp.getRight(),license);
                        }
                    }
                } catch (Exception e) {
                    log.error("访问编号为{}地磅led屏幕出现异常，当前车牌号为{}，异常原因为", location,license, e);
                }
            }else{
                log.error("当前车牌号为空，无法在Led屏上显示信息");
            }

            LicenseDto licenseDto = new LicenseDto();
            licenseDto.setLicense(jsonObject.get("license").toString());
            licenseDto.setDirection(Integer.valueOf(jsonObject.get("direction").toString()));
            licenseDto.setIp(jsonObject.get("ip").toString());
            licenseDto.setLocation(jsonObject.get("location").toString());
            licenseDto.setTime(Long.valueOf(jsonObject.get("time").toString()));
            licenseDto.setType(jsonObject.get("type").toString());
            //查询车牌队列的上一条数据是否是同一个车牌
            List<LicenseDto> licenseDtos = weighDao.selectLicenseMq(licenseDto);
            if (!CollectionUtils.isEmpty(licenseDtos)){
                LicenseDto licenseDto1 = licenseDtos.get(0);
                if(jsonObject.get("license").toString().equals(licenseDto1.getLicense())){
                    return;
                }
            }
            weighDao.insertLicenseMq(licenseDto);
        } else  {
            Object weight = jsonObject.get("weight");
            String location = jsonObject.get("location").toString();
            if("b006".equals(location) && weight!=null) {
                float weigh1 = Float.valueOf(weight.toString());
                if(weigh1<100){
                    if(weigh>100){
                        String replace = "00 10 01 04 00 0F 01 10 00 01 00 04 08 00 01 00 02 00 01 00 02".replace(" ", "");
                        byte[] bytes = HexUtil.Hex2Bytes(replace);
                        JSONObject postData = new JSONObject();
                        postData.put("data", new String(bytes));
                        try {
                            restTemplate.postForEntity(rasterUrl, postData, JSONObject.class).getBody();
                        }catch (Exception e){
                            log.error("调用光栅服务失败");
                        }

                        weigh=weigh1;
                    }else{
                        weigh=weigh1;
                    }
                }else{
                    //如果缓存里的重量小于100，来的车重量大于100,则亮红灯，如果本来也大于100，车重量也是100，灯不改变只把当前重量赋值一下
                    if(weigh<100){
                        String replace = "00 10 01 04 00 0F 01 10 00 01 00 04 08 00 02 00 01 00 02 00 01".replace(" ", "");
                        byte[] bytes = HexUtil.Hex2Bytes(replace);
                        JSONObject postData = new JSONObject();
                        postData.put("data", new String(bytes));
                        try {
                            restTemplate.postForEntity(rasterUrl, postData, JSONObject.class).getBody();
                        }catch (Exception e){
                            log.error("调用光栅服务失败");
                        }

                        weigh=weigh1;
                    }else {
                        weigh=weigh1;
                    }
                }
            }

        }

    }



//    public static void main(String[] args) {
//        String a="00 10 01 04 00 0F 01 10 00 01 00 04 08 00 01 00 02 00 01 00 02";
//        byte[] bytes = hexStringToByteArray(a);
//        System.out.println(bytes[1]);
//    }
    @Override
    protected AbstractBaseCallback getClazz() {
        return this;
    }

    @Override
    protected String getTopic() {
        return topic;
    }
}
